package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constant.RabbitConst;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.config.component.RabbitService;
import com.atguigu.gmall.mq.order.OrderCreateMsg;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author:lyd
 * @Date:2023/9/5 20:55
 * @Version:1.0
 * @Description  监听死信队列里面的消息
 **/
@Service
@Slf4j
public class OrderCloseListener {

    @Autowired
    OrderBizService bizService;
    @Autowired
    RabbitService rabbitService;

    @RabbitListener(queues = RabbitConst.QUEUE_ORDER_TIMEOUT)
    public void handle(Message message, Channel channel) throws IOException {

        //1、获取消息
        String msgJson = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();


        try {
            OrderCreateMsg msg = JSONs.jsonToObj(msgJson, OrderCreateMsg.class);
            log.info("正在关闭订单：订单id：{}, 用户id：{}", msg.getOrderId(), msg.getUserId());
            //2、业务处理
            bizService.closeOrder(msg.getOrderId(), msg.getUserId());
            //3、处理成功, 手动确认，回复ok
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            //4、处理失败
            log.error("关单处理失败: 消息内容：{}", msgJson);

            //5、重试
            //消息处理失败，一直重试
            //channel.basicReject(deliveryTag,true);
            //5、重试，继续关单，设定关5次
            //大于5次后不用重试，回复ack，让mq删除消息，并把消息数据记录数据库
            rabbitService.reTry(msgJson, channel, deliveryTag, 5);
        }
    }
}
